import VueRouter from 'vue-router'
import Vue from "vue";
import routes from "@/router/routes";
import store from '@/store'
Vue.use(VueRouter)
//把VueRouter原型对象的push先保存一份
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
//重写push,第一个参数：往哪里跳转
VueRouter.prototype.push=function (location,resolve,reject){
 if (resolve&&reject){
     //call都可以调用函数一次，篡改函数上下文一次
     originPush.call(this,location,resolve,reject)
 }else {
     originPush.call(this,location,()=>{},()=>{})
 }
}
//重写replace
VueRouter.prototype.push=function (location,resolve,reject){
    if (resolve&&reject){
        //call都可以调用函数一次，篡改函数上下文一次
        originReplace.call(this,location,resolve,reject)
    }else {
        originReplace.call(this,location,()=>{},()=>{})
    }
}
let router= new VueRouter({
    //配置路由
    routes,
    //滚动条
    scrollBehavior(to, from, savedPosition) {
        // 始终滚动到顶部
        return { y: 0 }
    }
})
//配置全局前置守卫
router.beforeEach(async (to,from,next)=>{
    //to:跳转到哪个地方,from:来自哪个地方，next：放行函数 next(path)放行到指定路由
    //获取token,未登录一定没有token
    let token=store.state.user.token
    let name=store.state.user.userInfo.name
    if (token){
        //用户已登录还想去/login
        if (to.path=='/login'||to.path=='/register'){
            next('/home')
        }else {
            if (name){
                next()
            }else {
               try {
                   //没有用户信息
                   //获取用户信息在首页展示
                   await store.dispatch('getUserInfo')
                   next()
               }catch (error){
                   //token失效了
                   await store.dispatch('userLogout')
                   next('/login')
               }
            }
        }
    }else {
        //未登录
        let toPath=to.path
        if (toPath=='/trade'||toPath.indexOf('/pay')!=-1||toPath.indexOf('/center')!=-1){
            next('/login?redirect'+toPath)
        }else {
            next()
        }
       next()
    }

})

export default router
